<template>
  <div>
    <el-button type="primary" @click="openAddDialog">新增分类</el-button>
    <el-table :data="classifies" style="width: 100%; margin-top: 20px">
      <el-table-column prop="id" label="ID" wid20h="80" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllClassifiesAPI,
  addClassifyAPI,
  updateClassifyAPI,
  deleteClassifyAPI,
} from '@/api/classifyAPI'

const classifies = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增分类')
const form = reactive({
  id: null,
  name: '',
})
const formRef = ref(null)
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
}
const isEdit = ref(false)

function fetchClassifies() {
  getAllClassifiesAPI().then((res) => {
    classifies.value = res.data || []
  })
}

function openAddDialog() {
  dialogTitle.value = '新增分类'
  isEdit.value = false
  form.id = null
  form.name = ''
  dialogVisible.value = true
}

function openEditDialog(row) {
  dialogTitle.value = '编辑分类'
  isEdit.value = true
  form.id = row.id
  form.name = row.name
  dialogVisible.value = true
}

function handleSubmit() {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    if (isEdit.value) {
      await updateClassifyAPI({ id: form.id, name: form.name })
      ElMessage.success('修改成功')
    } else {
      await addClassifyAPI({ name: form.name })
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchClassifies()
  })
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
    type: 'warning',
  })
    .then(async () => {
      await deleteClassifyAPI(id)
      ElMessage.success('删除成功')
      fetchClassifies()
    })
    .catch(() => {})
}

onMounted(fetchClassifies)
</script>
